<template>
  <view>
    <uni-forms
      ref="formRef"
      label-position="top"
      :model="formData"
      :rules="rules"
      label-width="100vw"
      :disabled="disabled"
    >
      <template v-for="item in options">
        <slot
          :name="`before${item.prop}`"
          :formData="formData"
          :option="item"
        ></slot>
        <slot :name="item.prop" :formData="formData" :option="item">
          <uni-forms-item
            :key="item.prop"
            :label="item.label"
            :required="item.required || false"
            :rules="
              item.required
                ? [
                    {
                      required: true,
                      errorMessage: '字段为必填项',
                    },
                  ]
                : []
            "
            :name="item.prop"
          >
            <uni-easyinput
              :style="{
                border: 'none',
              }"
              v-if="item.type == 'input'"
              @change="change(item.prop, $event)"
              type="text"
              v-model="formData[item.prop]"
              :placeholder="placeholders[item.type] + item.label"
              :disabled="disabled"
            />
            <!-- <uni-data-checkbox
              style="border: none"
              v-else-if="item.type == 'zyry'"
              v-model="formData[item.prop]"
              :localdata="selectZyry"
              @change="changeZyry(item, $event)"
              :placeholder="placeholders[item.type] + item.label"
              :disabled="disabled"
              :multiple="item.multiple"
            ></uni-data-checkbox> -->
            <rudon-multiSelector
              v-else-if="item.type == 'zyry'"
              welcome="请选择"
              :is_using_slot="false"
              :is_using_icon="true"
              :localdata="selectZyry"
              v-model="formData[item.prop]"
              @change="changeZyry(item, $event)"
            ></rudon-multiSelector>
            <rudon-multiSelector
              v-else-if="item.type == 'glzyp'"
              welcome="请选择"
              :is_using_slot="false"
              :is_using_icon="true"
              :localdata="selectList"
              v-model="formData[item.prop]"
              @change="changeZyry(item, $event)"
            ></rudon-multiSelector>
            <uni-combox
              :candidates="item.optionItems"
              v-else-if="item.type == 'combox'"
              v-model="formData[item.prop]"
            ></uni-combox>
            <rudon-multiSelector
              v-else-if="item.type == 'mselect'"
              welcome="请选择"
              :is_using_slot="false"
              :is_using_icon="true"
              :localdata="item.optionItems"
              v-model="formData[item.prop]"
            ></rudon-multiSelector>
            <uni-data-select
              style="border: none"
              v-else-if="item.type == 'select'"
              v-model="formData[item.prop]"
              :localdata="item.optionItems"
              @change="change(item.prop, $event)"
              :placeholder="placeholders[item.type] + item.label"
              :disabled="disabled"
            ></uni-data-select>
            <uni-datetime-picker
              v-else-if="
                ['datetime', 'date', 'datetimerange', 'daterange'].includes(
                  item.type
                )
              "
              :type="item.type"
              v-model="formData[item.prop]"
              @change="changeTime(item.prop, $event, item.type)"
              :placeholder="placeholders[item.type] + item.label"
              :hide-second="true"
              :disabled="disabled"
            />
            <!-- 自动计算结束时间组件 -->
            <view v-else-if="['newdatetimerange'].includes(item.type)">
              <uni-datetime-picker
                v-model="formData[item.prop][0]"
                placeholder="请选择动火作业开始时间"
                type="datetime"
                :hide-second="true"
                @change="changeJobTime(item.prop, $event, item.type)"
              ></uni-datetime-picker>
              <uni-datetime-picker
                v-model="formData[item.prop][1]"
                type="datetime"
                :hide-second="true"
                placeholder="自动带出动火作业结束时间"
              ></uni-datetime-picker>
            </view>

            <uni-data-checkbox
              v-else-if="item.type == 'radio' || item.type == 'checkbox'"
              v-model="formData[item.prop]"
              :localdata="item.optionItems"
              :multiple="item.type == 'checkbox'"
              @change="change(item.prop, $event)"
              :disabled="disabled"
            ></uni-data-checkbox>
            <uploadFileVue
              v-if="item.type == 'file'"
              v-model="formData[item.prop]"
              @change="changeFile(formData[item.prop])"
              :disabled="disabled"
            ></uploadFileVue>
          </uni-forms-item>
        </slot>
      </template>
    </uni-forms>
  </view>
</template>

<script setup>
import { onMounted, ref, defineProps, defineEmits, watch, nextTick } from "vue";
import { router } from "@/router/index.js";
import uploadFileVue from "@/components/uploadFile.vue";
import { formatDate } from "@/utils/index.js";

const placeholders = {
  datetime: "请选择",
  date: "请选择",
  datetimerange: "请选择",
  daterange: "请选择",
  select: "请选择",
  input: "请输入",
  zyry: "请选择",
};
const emits = defineEmits(["onChange", "onSubmit", "onSave"]);
const changeFile = (file) => {};
const props = defineProps({
  rules: {
    type: Object,
    default: () => ({}),
  },
  formOption: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  zyryList: {
    type: Array,
    default: () => [],
  },
  zypList: {
    type: Array,
    default: () => [],
  },
  jobType: String,
});

const submitForm = async () => {
  if (res) {
    formatTimes();
    emits("onSubmit", {
      ...keepData.value,
      ...formData.value,
    });
  } else {
    return false;
  }
};

const options = ref([]);
const formData = ref({});
const keepData = ref({});

function setFormData(data = {}) {
  keepData.value = JSON.parse(JSON.stringify(data));
  formData.value = {
    ...data,
  };
}

function setOptions(option) {
  if (option) {
    options.value = JSON.parse(JSON.stringify(option));
  } else {
    options.value = [];
  }
}
const formRef = ref();
async function getFormData() {
  try {
    const res = await formRef.value.validate();
    formatTimes();
    return {
      ...keepData.value,
      ...formData.value,
    };
  } catch (e) {
    return false;
  }
}

const getSaveFormData = () => {
  formatTimes();
  return {
    ...keepData.value,
    ...formData.value,
  };
};
const change = (key, value) => {
  emits("onChange", {
    key,
    value,
  });
};
defineExpose({
  setFormData,
  setOptions,
  getFormData,
  submitForm,
  getSaveFormData,
});

const selectZyry = ref([]);
const selectList = ref([]);
const zyzsbh = ref({});
watch(
  () => props.zyryList,
  () => {
    selectZyry.value = props.zyryList.map((item) => ({
      value: item.label || item.name,
      text: item.label || item.name,
    }));
  }
);
watch(
  () => props.zypList,
  () => {
    selectList.value = props.zypList;
  }
);
watch(
  () => props.formOption,
  () => {
    if (props.formOption) {
      options.value = JSON.parse(JSON.stringify(props.formOption));
    } else {
      options.value = [];
    }
  }
);
const changeTime = (prop, value, type) => {};
// 自动计算时间
const workTime = ref({
  "特级（8H）": 8,
  "一级（8H）": 8,
  "二级（72H）": 72,
});
const changeJobTime = (prop, value, type) => {
  nextTick(() => {
    if (prop == "jobDate" && props.jobType == 2) {
      let beginTime = getDateFromString(value);
      formData.value[prop][1] = formatDate(
        beginTime.setHours(
          beginTime.getHours() + workTime.value[formData.value.dhzyjb]
        )
      );
    }
  });
};
function getDateFromString(str) {
  var reg = /^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/;
  var s = str.match(reg);
  var result = "";
  if (s) {
    result = new Date(s[1], s[2] - 1, s[3], s[4], s[5], s[6]);
  }
  return result;
}

// 提交前自动补充时分
const formatTimes = () => {
  options.value.forEach((item) => {
    if (item.type.includes("time")) {
      let value = formData.value[item.prop];
      if (item.type.includes("range")) {
        value = formData.value[item.prop] || [];
        let values = [];
        if (value.length == 0) return;
        value.forEach((ele, index) => {
          if (ele.length < 12) {
            values[index] = ele + "00:00";
          } else {
            values[index] = ele;
          }
        });
        formData.value[item.prop] = values;
      } else {
        if (!value) return;
        formData.value[item.prop] = value.length < 12 ? value + "00:00" : value;
      }
    }
  });
};

// 选择作业人员 自动带出票证号
const changeZyry = (option, val) => {
  if (option.bh) {
    const zsbh = props.zyryList
      .filter((item) => val.includes(item.name))
      .filter((user) => user.zsh)
      .map((user) => user.zsh)
      .join(",");
    if (zsbh) {
      formData.value[option.bh] = zsbh;
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff !important;
}

.is-input-border {
  border: none !important;
}

.checklist-group {
  padding: 10px;
}

.btn-box {
  display: flex;
  justify-content: space-between;
}
</style>
